<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
        <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false"> </el-alert>
       <!-- 选择分类商品区域 -->
      <el-row class="bg_ptn">
          <el-col>
              <span>选择商品分类: </span>
              <!-- 级联选择器 -->
              <el-cascader
                v-model="slectedKeys"
                :options="cateList"
                expand-trigger="hover"
                :props="caseProps"
                @change="handleChange"
                clearable>
              </el-cascader>
          </el-col>
      </el-row>
        <!--tab标签页 -->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="btn_disable" @click="addParams">添加参数</el-button>
                <!-- 动态表格 -->
                <el-table :data="manyTableData" border stripe>
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag v-for="(item,index) in scope.row.attr_val" :key="index" closable @close="closeTag(index,scope.row)">{{item}}</el-tag>
                            <!-- 动态tab -->
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                       <template slot-scope="scope">
                            <el-button type="primary" size="mini" @click="editParams(scope.row.attr_id)"><i class="el-icon-edit"></i> 编辑</el-button>
                            <el-button type="danger" size="mini" @click="deleteParams(scope.row.attr_id)"><i class="el-icon-delete"></i> 删除</el-button>
                       </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only" border stripe>
                 <el-button type="primary" :disabled="btn_disable" @click="addParams">添加属性</el-button>
                  <!-- 静态属性 -->
                <el-table :data="onlyTableData">
                     <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag v-for="(item,index) in scope.row.attr_val" :key="index" closable @close="closeTag(index,scope.row)">{{item}}</el-tag>
                            <!-- 动态tab -->
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" @click="editParams(scope.row.attr_id)"><i class="el-icon-edit"></i> 编辑</el-button>
                            <el-button type="danger" size="mini" @click="deleteParams(scope.row.attr_id)"><i class="el-icon-delete"></i> 删除</el-button>
                       </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- addDialog -->
    <el-dialog
        :title="'添加'+addMess"
        :visible.sync="addDialog"
        width="50%"
        @close="addDialogClosed"
        >
        <el-form ref="addform" :model="addform" :rules="addRules" label-width="80px">
            <el-form-item :label="addMess" prop="attr_name">
                <el-input v-model="addform.attr_name" @clear="clearInput"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialog= false">取 消</el-button>
            <el-button type="primary" @click="submitAddParams">确 定</el-button>
        </span>
    </el-dialog>
        <!-- editDialog -->
         <el-dialog
        :title="'修改'+addMess"
        :visible.sync="editDialog"
        width="50%"
        @close="editDialogClosed"
        >
        <el-form ref="editForm" :model="editForms" :rules="addRules" label-width="80px">
            <el-form-item :label="addMess" prop="attr_name">
                <el-input v-model="editForms.attr_name" @clear="clearInput"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialog= false">取 消</el-button>
            <el-button type="primary" @click="submitEditParams">确 定</el-button>
        </span>
        </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
        //分类数据列表
        cateList:[],
        //参数列表
        paramsList:[],
        manyTableData:[],
        onlyTableData:[],
        editDialog:false,
        attr_id:0,
        editForms:{},
        addform:{
            attr_name:''
        },
        addRules:{
            attr_name:[
                  { required: true, message: '请输入参数名称', trigger: 'blur' }
            ]
        },
        addDialog:false,
        //tab选中
        activeName:'many',
        //选中商品
        slectedKeys:[],
        caseProps:{
            value:'cat_id',
            label:'cat_name',
            children:'children'
        }
    };
  },
  created() {
      this.getCateList();
  },
  methods: {
      //获取分类参数列表数据
      async getParamsList(){
          const {data:res}=await this.$http.get(`categories/${this.get_id}/attributes`,{
            params:{
                sel:this.activeName
            }
        })
        if(res.meta.status!==200) return this.$message.warning('请选择商品分类')
        //
        res.data.forEach(item=>{
            item.attr_val=item.attr_val? item.attr_val.split(' '):[];
            item.inputVisible=false;
            item.inputValue='';
        })
        console.log(res.data)
        if(this.activeName=='many'){
            this.manyTableData=res.data;
            console.log(this.manyTableData)
        }else{
            this.onlyTableData=res.data;
        }
      },
     
      //获取所有商品分类数据列表
      async getCateList(){
          const {data:res}=await this.$http.get('categories');
          if(res.meta.status!==200) return this.$message.error('获取数据失败！')
          this.cateList=res.data;
          console.log(this.cateList)
      },
      //选择改变时候触发
      async handleChange(){
          //如果选择的不是三级分类，则清空
          if(this.slectedKeys.length!==3){
              this.slectedKeys=[]
              this.manyTableData=[]
              this.onlyTableData=[]
              return
          }
          this.getParamsList();
      },
      //tab标签页选中
      handleTabClick(){
          console.log(this.activeName)
          this.getParamsList();
      },
      //添加参数
      addParams(){
          this.addDialog=true
      },
      //监听dialog关闭
      addDialogClosed(){
          this.$refs.addform.resetFields();
      },
      submitAddParams(){
          this.$refs.addform.validate(async valid=>{
              if(!valid) return this.$message.error('表单验证不通过')
              var {data:res}=await this.$http.post(`categories/${this.get_id}/attributes`,{
                  attr_name:this.addform.attr_name,
                  attr_sel:this.activeName
              })
              if(res.meta.status!==201) return this.$message.error('添加失败')
              this.$message.success('添加成功')
              this.getParamsList();
              this.addDialog=false;
          })
      },
      clearInput(){
          this.manyTableData=[];
          this.onlyTableData=[]
      },
      //编辑参数
      async editParams(attrid){
         this.attr_id=attrid;
         var {data:res}=await this.$http.get(`categories/${this.get_id}/attributes/${attrid}`,{
                  attr_sel:this.activeName
              })
              if(res.meta.status!==200) return this.$message.error('获取参数失败')
              this.editForms=res.data;
              console.log(this.editForms)
              this.editDialog=true;
      },
      editDialogClosed(){
          this.$refs.editForm.resetFields();
      },
      //提交修改参数
      submitEditParams(){
          this.$refs.editForm.validate( async valid=>{
              if(!valid) return this.$message.error('表单验证不通过')
              //请求提交
               var {data:res}=await this.$http.put(`categories/${this.get_id}/attributes/${this.attr_id}`,{
                  attr_sel:this.activeName,
                  attr_name:this.editForms.attr_name
              })
              if(res.meta.status!==200) return this.$message.error('修改失败')
              this.$message.success('修改成功')
              this.getParamsList();
              this.editDialog=false;
          })
      },
      //删除参数
      async deleteParams(attrid){
          var confirm=await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        if(confirm!=='confirm') return this.$message.info('已取消删除')
        var {data:res}=await this.$http.delete(`categories/${this.get_id}/attributes/${attrid}`)
        if(res.meta.status!==200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParamsList();

      },
      //动态tab
      async handleInputConfirm(role){
          let inputValue=role.inputValue;
          if(inputValue){
              role.attr_val.push(inputValue)
          }
          role.inputValue=''
          role.inputVisible=false;

         this.saveAttrValue(role);
        //   var {data:res}=await this.$http.delete(`categories/${this.get_id}/attributes/${role.attr_id}`,{
        //       attr_name:role.attr_name,
        //       attr_sel:role.attr_sel,
        //       attr_vals:role.attr_val.join(' ')
        //   })
        // if(res.meta.status!==200) return this.$message.error('更新失败')
        // this.$message.success('更新成功')
      },
      showInput(role){
           role.inputVisible=true;
           this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
             });
      },
      async saveAttrValue(role){
           var {data:res}=await this.$http.delete(`categories/${this.get_id}/attributes/${role.attr_id}`,{
              attr_name:role.attr_name,
              attr_sel:role.attr_sel,
              attr_vals:role.attr_val.join(' ')
          })
        if(res.meta.status!==200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
      },
      //删除可选项
      closeTag(index,role){
          role.attr_val.splice(index,1)
          this.saveAttrValue(role);
      }
  },
  computed:{
      btn_disable(){
          //如果不是选择第三级分类，则返回ture,否则返回false
           if(this.slectedKeys.length!==3){
               return true
           }
           return false;
      },
      get_id(){
          if(this.slectedKeys.length==3){
              return this.slectedKeys[2]
          }
          return null;
      },
      addMess(){
          if(this.activeName=='many'){
              return '动态参数'
          }
          return '静态属性'
      }
  }
};
</script>
<style lang="less" scoped>
.bg_ptn{
    margin-top: 20px;
}
.input-new-tag{
    width: 130px;
}
.el-tag{
    margin: 15px;
}
</style>